package com.mutouren.modules.ca.service.impl;

import java.util.List;
import java.util.Random;

import javax.annotation.Resource;

import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.stereotype.Service;

import com.mutouren.common.entity.Result;
import com.mutouren.common.entity.ResultCode;
import com.mutouren.common.entity.ResultInfo;
import com.mutouren.common.entity.ValidState;
import com.mutouren.common.orm.spring.BaseServiceImpl;
import com.mutouren.common.utils.DigestUtils;
import com.mutouren.modules.ca.dao.UserDao;
import com.mutouren.modules.ca.model.User;
import com.mutouren.modules.ca.service.UserService;

@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {
	
	private static final String defaultPassword = "123456";
	private static final String md5PasswordFormat = "mtr%s%s";

	@Resource
	private UserDao userDao;

	@Override
	public void afterPropertiesSet() throws Exception {
		this.baseDao = userDao;
	}
	
	private User buildLoginUser(String loginName) {
		User result = new User();
		
		if (loginName.indexOf("@") >= 0) {
			result.setEmail(loginName);
		} else if (NumberUtils.isNumber(loginName) && loginName.length() == 11) {
			result.setMobile(loginName);
		} else {
			result.setUserName(loginName);
		}
		
		return result;
	}

	@Override
	public ResultInfo<User> login(String loginName, String password) {
		ResultInfo<User> result = new ResultInfo<User>();
		result.setCode(ResultCode.FAIL.value);
		User user = userDao.getByIdentity(buildLoginUser(loginName));
		
		if ((user == null) || (user.getValidState() != ValidState.Normal)) {
			result.setMessage("登录名无效");
			return result;
		}		
		
		String md5Password = DigestUtils.MD5(String.format(md5PasswordFormat, password, user.getSalt())); 
		if (!md5Password.equals(user.getPassword())) {
			result.setMessage("密码错误");
			return result;
		}		
		
		userDao.updateLastLoginTime(user.getUserId());
		
		result.setCode(ResultCode.SUCCESS.value);
		result.setInfo(user);
		return result;
	}

	@Override
	public Result register(User user) {
		Result result = new Result();
		result.setCode(1); // fail
		
		List<User> listUser = userDao.getByIdentityForRegister(user);
		if (listUser.size() > 0) return result;
		
		user.setSalt(new Random().nextInt(1000000));
		String md5Password = DigestUtils.MD5(String.format(md5PasswordFormat, defaultPassword, user.getSalt())); 
		user.setPassword(md5Password);		
		userDao.insert(user);
		
		result.setCode(0); // success		
		return result;
	}

	@Override
	public Result modifyPassword(long userId, String oldPassword, String newPassword) {
		Result result = new Result();
		
		User user = userDao.get(userId);
		if (user == null) {
			result.setCode(ResultCode.FAIL.value);
			result.setMessage("用户无效");
			return result;			
		}		
		
		String md5PasswordOld = DigestUtils.MD5(String.format(md5PasswordFormat, oldPassword, user.getSalt()));
		if (!md5PasswordOld.equals(user.getPassword())) {
			result.setCode(ResultCode.FAIL.value);
			result.setMessage("原密码错误");
			return result;
		}
				
		String md5PasswordNew = DigestUtils.MD5(String.format(md5PasswordFormat, newPassword, user.getSalt()));
		userDao.modifyPassword(userId, md5PasswordNew);
		result.setCode(ResultCode.SUCCESS.value);
		return result;
	}
	
	@Override
	public void resetPassword(long userId) {
		User user = userDao.get(userId);		
		String md5PasswordNew = DigestUtils.MD5(String.format(md5PasswordFormat, defaultPassword, user.getSalt())); 
		user.setPassword(md5PasswordNew);
		userDao.modifyPassword(userId, md5PasswordNew);		
	}

	@Override
	public void verifyEmail(long userId, String email) {
		userDao.verifyEmail(userId, email, true);
	}

	@Override
	public void verifyMobile(long userId, String mobile) {
		userDao.verifyMobile(userId, mobile, true);	
	}

	@Override
	public void approve(long userId) {
		userDao.approve(userId, true);		
	}
	
	@Override
	public int add(User user) {		
		throw new RuntimeException("not permit direct call the add()");
	}	
	
}
